package com.dhu.demo.JWT;

import java.util.Calendar;
import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JWTEntity {

    public static String KEY = "duxinyangzhongchuanxinzhengguangyi";

    public static String createToken(String account, String password,String level) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 120);//登录两个小时后过期
        Date expireDate = nowTime.getTime();

        String token = JWT.create().withAudience(account)
                .withIssuedAt(new Date())
                .withExpiresAt(expireDate)
                .withClaim("level",level)
                .sign(Algorithm.HMAC256(account+password+KEY));
        System.out.println(token);
        return token;
    }

    /**
     * 检验合法性，其中secret参数就应该传入的是用户的password
     * @param token
     * @throws JWTVerificationException
     */
    public static boolean verifyToken(String token, String secret) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret + KEY)).build();
            jwt = verifier.verify(token);
        }catch (JWTVerificationException e){
            return false;
        }
        return true;
    }

    /**
     * 获取签发对象
     */
    public static String getAudience(String token) {
        String audience = null;
        try {
            audience = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            //这里是token解析失败
            return null;
        }
        return audience;
    }

}
